<?php
include ('lib/config.php');
include ('lib/weibooauth.php');
include ('lib/twitteroauth.php');
include ('lib/oauth_lib.php');
include ('lib/twitter.php');

function strlength($string){
	return mb_strlen($string,'UTF-8');
}
function strcut($string,$start=0,$length=140){
	return 	mb_substr($string,$start,$length,'UTF-8');
}


if(!is_file(WB_OAUTH)){
	die('未获取新浪微博OAuth授权,<a href="index.php">返回首页</a>');
}

list($wb_oauth_token,$wb_oauth_token_secret) = explode("\n",file_get_contents(WB_OAUTH));
$weibo = new WeiboClient(WB_AKEY , WB_SKEY , $wb_oauth_token , $wb_oauth_token_secret);
$status  = $weibo->user_timeline(1,20,WB_USER);

if(!empty($status)){
	$old_max_id = $max_id = is_file(WB_ID) ? file_get_contents(WB_ID) : 0;
			
	$wb = array();
	foreach($status as $t){
		if($t['id'] > $old_max_id){
			$max_id = $t['id'] > $max_id ? $t['id'] : $max_id;
			$wb[] = $t;
		}		
	}
	
	file_put_contents(WB_ID,$max_id);
}
krsort($wb);

if(!empty($wb)){
	$twitter = getTwitter();
	if(!$twitter){
		die('无法登陆twitter');
	}
	
	foreach($wb as $status){
				
		if(!$status['retweeted_status'] && $status['text']!='转发微博。' && strpos($status['text'],'回复') === false && strpos($status['text'],'//@') === false){
			$original_pic = $status['original_pic'];
			if($original_pic){
				if(strlength($status['text']) == 140){
					$content = $status['text'];
				}
				else{
					$content = $status['text'].'[图]';
					$new_content = $content.$original_pic;
					if(strlength($new_content) > 140){
						$shorturl = file_get_contents('http://is.gd/api.php?longurl='.$original_pic);
						$new_content = $content.$shorturl;
						if(strlength($new_content) > 140){
							$new_content = strcut($new_content,0,140-strlen($shorturl)-6).'...[图]'.$shorturl;
						}
					}
					$content = $new_content;
				}
			}
			else{
				$content = strlength($status['text']) > 140 ? strcut($status['text'],0,137).'...' : $status['text'];
			}

			$twitter->update($content);
			
		}	
	}	
}

file_put_contents(UPDATE_FILE,date('Y-m-d H:i:s'));

echo '运行完毕,<a href="index.php">返回首页</a>';
?>